﻿using black_screen_client.Models;
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;

namespace black_screen_client
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Screen : Window
    {
        public DateTime dt = DateTime.Now;
        public event Action<int>  LogRequest;
        public int groupId;
        private bool isPreview = false;
        public string groupName = "分组名";
        public bool isBlackScreen = false;

        //private static string iniFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config", "sysConfig.ini");
        //private static IniFile iniFile = new IniFile(iniFilePath);

        public Screen(System.Windows.Media.Brush backgroundColor, System.Windows.Media.Brush textColor)
        {
            InitializeComponent();
            SourceInitialized += Screen_SourceInitialized;
            Background = backgroundColor;
            txtBsTime.Foreground = textColor;
            txtGroupName.Foreground = textColor;

            //string host = iniFile.Read("ServerName", "hostname");
            //int requestedScreen = Convert.ToInt32(iniFile.Read("DisplayScreenInfo", "screenIndex"));


            //txtGroupName.Text = $"黑屏状态 - {host}";

            //var allScreens = global::System.Windows.Forms.Screen.AllScreens;

            //if (allScreens != null && allScreens.Length > 0)
            //{
            //    System.Windows.Forms.Screen targetScreen;

            //    if (allScreens.Length > 1 && requestedScreen >= 0 && requestedScreen < allScreens.Length)
            //    {
            //        // 多屏：使用指定的屏幕
            //        targetScreen = allScreens[requestedScreen];
            //    }
            //    else
            //    {
            //        // 单屏或无效索引：使用主屏幕
            //        targetScreen = System.Windows.Forms.Screen.PrimaryScreen;
            //    }

            //    // 设置窗口大小为所选屏幕的可用工作区
            //    this.Width = targetScreen.Bounds.Width;
            //    this.Height = targetScreen.Bounds.Height;

            //}

            // txtInfo.Foreground = textColor;
            //txtDuration.Foreground = textColor;
            //lbl_curGroup.Foreground = textColor;
            //txt_groupName.Foreground = textColor;
            CompositionTarget.Rendering += CompositionTarget_Rendering;
         
        }

        private void Screen_SourceInitialized(object sender, EventArgs e)
        {
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            HwndSource.FromHwnd(hwnd).AddHook(WndProc);
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            const int WM_KEYDOWN = 0x100;
            const int WM_SYSKEYDOWN = 0x104;

            if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN)
            {
                // 这里处理按键事件
                int key = wParam.ToInt32() & 0xFF;
                // 你可以根据key值来判断是哪个键被按下
                // 例如，如果(key == 84) 表示按下了 'T' 键

                // 标记事件已处理
                handled = true;
            }

            return IntPtr.Zero;
        }
    
    private const int WS_EX_TRANSPARENT = 0x20;

        private const int GWL_EXSTYLE = -20;

        [DllImport("user32", EntryPoint = "SetWindowLong")]
        private static extern uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);

        [DllImport("user32", EntryPoint = "GetWindowLong")]
        private static extern uint GetWindowLong(IntPtr hwnd, int nIndex);

        //ESC退出<最小化到任务栏>
        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape)  //按esc退出
            {
                e.Handled = true;

                if (!isPreview)
                    this.WindowState = WindowState.Minimized;
                else
                    this.Close();
            }
            else if(e.Key ==Key.Escape && (Keyboard.Modifiers &(ModifierKeys.Control)) ==(ModifierKeys.Control))
            {
                e.Handled= true;
                this.WindowState = WindowState.Maximized;
            }
        }

        public void setPreview(bool isPreview)
        {
            this.isPreview = isPreview;
        }

        private int nMouseDownClick = 0;

        //双击-->最近事件弹窗
        public void Image_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            nMouseDownClick += 1;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 300);
            timer.Tick += (s, e1) => { timer.IsEnabled = false; nMouseDownClick = 0; };
            timer.IsEnabled = true;
            if (nMouseDownClick % 2 == 0)
            {
                timer.IsEnabled = false;
                nMouseDownClick = 0;
              
            }
        }     

        //当前时间显示
        public void CompositionTarget_Rendering(object sender, EventArgs e)
        {

            BlackScreenStartData blackScreenStartData = new BlackScreenStartData();
            TimeSpan duration = DateTime.Now - Convert.ToDateTime(dt);

            txtBsTime.Text = duration.ToString("%d")+"天 "+ duration.ToString("%h") +"小时 "+ duration.ToString("%m") + "分钟";
        }

        public void UpdateOpacity(double opacity)
        {
            opacity = Math.Max(0, Math.Min(1, opacity));

            this.Background.Opacity = opacity;
            txtBsTime.Foreground.Opacity = opacity;
            txtGroupName.Foreground.Opacity = opacity;
            //txtInfo.Foreground.Opacity = opacity;
            //imgHoneywell.Opacity = opacity;
        }

        private void ScreenClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (isBlackScreen)
            {
                System.Windows.MessageBox.Show("不能手动关闭黑屏！", "提示");
                e.Cancel = true;
                return;
            }
            else
            {
                e.Cancel = false;
            }
        }

        private void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (isPreview)
            {
                this.Close();
            }
            else
            {
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.LogRequest?.Invoke(groupId);
                   // Logger.Singleton.Info("双击打开最近事件窗口");
                }));

                //RencentEvents rencentEvents = new RencentEvents();
                //rencentEvents.Show();
                e.Handled = true;
            }
        }
    }

}
